<script setup lang="ts">
import { useScrollViewRefresh, useSkeleton } from '@/composables'
import { OrderState } from '@/constants/constants'
import { orderStateList } from '@/constants/constants'
import {
  deleteMemberOrderAPI,
  getMemberOrderAPI,
  putMemberOrderReceiptByIdAPI,
} from '@/services/order'
import type { OrderItem } from '@/types/order'
import type { OrderListParams } from '@/types/order'
import { onMounted, ref } from 'vue'
import ListSkeleton from './ListSkeleton.vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 定义 porps
const props = defineProps<{
  orderState: number
}>()

// 请求参数
const queryParams: OrderListParams = {
  page: 1,
  pageSize: 5,
  orderState: props.orderState,
}

// 获取订单列表
const orderList = ref<OrderItem[]>([])
// 订单总页数
const totalPages = ref(0)

// 获取第一页数据
const getMemberOrderDataFirstPage = async () => {
  queryParams.page = 1
  const res = await getMemberOrderAPI(queryParams)
  orderList.value = res.result.items
  totalPages.value = res.result.pages
}

// 获取更多数据
const getMemberOrderData = async () => {
  const res = await getMemberOrderAPI(queryParams)
  console.log(queryParams.orderState)
  orderList.value.push(...res.result.items)
  totalPages.value = res.result.pages
}

// 控制骨架屏显示和隐藏
const { isShowSkeleton, skeletonController } = useSkeleton()

onMounted(() => {
  skeletonController(async () => {
    await getMemberOrderData()
  })
})

// 滚动触底加载更多数据
const onScrolltolower = () => {
  // 如果不是最后一页，则加载下一页数据
  if (queryParams.page! < totalPages.value) {
    // 获取下一页订单数据
    queryParams.page!++
    getMemberOrderData()
  }
}

// 未支付订单去支付
const onGoToPay = (orderId: string) => {
  uni.navigateTo({ url: `/pages-order/detail/detail?id=${orderId}` })
}

// 确认收货
const onOrderConfirm = async (orderId: string) => {
  // 二次确认弹窗
  uni.showModal({
    title: '温馨提示',
    content: '为了保障您的权益，请收到货并确认无误后，再确认收货',
    success: async (success) => {
      if (success.confirm) {
        const res = await putMemberOrderReceiptByIdAPI(orderId)
        // 更新订单状态
        orderList.value.find((item) => {
          if (item.id === orderId) {
            item = {
              ...res.result,
              totalNum: item.totalNum,
            }
          }
        })
      }
    },
  })
}

// 下拉刷新
const { isTriggered, refreshController } = useScrollViewRefresh()
const onRefresherrefresh = () => {
  refreshController(async () => {
    // 重新获取第一页数据
    await getMemberOrderDataFirstPage()
  })
}

// 删除订单
const onDeleteMemberOrder = async (orderId: string) => {
  uni.showModal({
    title: '温馨提示',
    content: '您确定要删除订单吗？',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({
          title: '正在删除...',
        })
        // 删除
        await deleteMemberOrderAPI({ ids: [orderId] })
        // 重新获取第一页数据
        await getMemberOrderDataFirstPage()
        uni.hideLoading()
        uni.showToast({
          title: '删除成功',
        })
      }
    },
  })
}
</script>

<template>
  <!-- 骨架屏 -->
  <ListSkeleton v-if="isShowSkeleton" />
  <!-- 主内容 -->
  <scroll-view
    v-else
    scroll-y
    class="orders"
    enable-back-to-top
    @scrolltolower="onScrolltolower"
    :refresher-triggered="isTriggered"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
  >
    <view class="card" v-for="order in orderList" :key="order.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ order.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStateList[order.orderState].text }}</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <text
          v-if="order.orderState >= OrderState.DaiPingJia"
          class="icon-delete"
          @tap="onDeleteMemberOrder(order.id)"
        ></text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <navigator
        v-for="item in order.skus"
        :key="item.id"
        class="goods"
        :url="`/pages-order/detail/detail?id=${order.id}`"
        hover-class="none"
      >
        <view class="cover">
          <image mode="aspectFit" :src="item.image"></image>
        </view>
        <view class="meta">
          <view class="name ellipsis">{{ item.name }}</view>
          <view class="type">{{ item.attrsText }}</view>
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ order.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount"> <text class="symbol">¥</text>{{ order.payMoney }}</text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="order.orderState === OrderState.DaiFuKuan">
          <view class="button primary" @tap="onGoToPay(order.id)">去支付</view>
        </template>
        <template v-else>
          <navigator
            class="button secondary"
            :url="`/pages-order/create/create?orderId=${order.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <!-- 待收货状态: 展示确认收货 -->
          <view
            v-if="order.orderState === OrderState.DaiShouHuo"
            class="button primary"
            @tap="onOrderConfirm(order.id)"
            >确认收货</view
          >
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ queryParams.page! >= totalPages ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
</template>

<style lang="scss">
// 订单列表
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
